using System;
using System.Collections.Generic;
using System.Text;

namespace Hawkeye
{
  public class FrequencyTableProducer : HawkService.IService
  {
    public static string T(string tag, string html)
    {
      return "<" + tag + ">" + html + "</" + tag + ">";
    }

    static string rn = "\r\n";
    public string ProduceFrequenceReport(Dictionary<string, int> freqTable)
    {
      string columnHeaders = BuildRow(T("b", "class"), T("b", "usage count"));
      string rows = BuildRows(freqTable);

      return T("html", T("table", rn + columnHeaders + rows));
    }

    private string BuildRows(Dictionary<string, int> freqTable)
    {
      List<string> classnames = GetFreqSortedClassnames(freqTable);
      string rows = "";
      foreach (string classname in classnames)
        rows += BuildRow(classname, freqTable[classname].ToString());
      return rows;
    }

    private string BuildRow(string c1, string c2)
    {
      return T("tr", T("td", c1) + T("td", c2)) + rn;
    }

    private static List<string> GetFreqSortedClassnames(Dictionary<string, int> freqTable)
    {
      List<string> classnames = new List<string>(freqTable.Keys);
      classnames.Sort(delegate(string c1, string c2)
      {
        return freqTable[c2].CompareTo(freqTable[c1]);
      });
      return classnames;
    }
  }
}
